package com.test.phoneCode;


import redis.clients.jedis.Jedis;

import java.util.Random;

public class PhoneCode {

    public static void main(String [] args){
//        verifyCode("123333333331");

        checkingCode("123333333331","508501");
    }

    //验证
    public static void checkingCode(String phone , String code){
        Jedis jedis = new Jedis("192.168.0.200",6379);

        String codeKey = "VerifyCode"+phone+":code";
        String redisCode = jedis.get(codeKey);
        Long ttl = jedis.ttl(codeKey);
        System.out.println(ttl);
        if(ttl != -2) {
            if (redisCode.equals(code)) {
                System.out.println("Checking Success!");
            } else {
                System.out.println("验证码输入错误或已过期！");
            }
        }else {
            System.out.println("验证码输入错误或已过期！");
        }
    }

    //发送验证码,每个手机号每天只能发送三次
    public static void verifyCode(String phone){
        Jedis jedis = new Jedis("192.168.0.200",6379);

        //手机发送次数
        String countKey = "VerifyCode"+phone+":count";
        //验证码
        String codeKey = "VerifyCode"+phone+":code";
        //获取手机发送次数
        String count = jedis.get(countKey);
        if(count == null){
            jedis.setex(countKey,24*60*60,"1");
        }else if(Integer.parseInt(count)<=2){
            jedis.incr(countKey);
        }else if(Integer.parseInt(count)>2){
            System.out.println("今天发送次数已经到达三次");
            jedis.close();
        }
        //将验证码存入到redis中
        String vcode = getCode();
        jedis.setex(codeKey,120,vcode);
        jedis.close();

    }

    //生成验证码
    public static String getCode(){
        Random random = new Random();
        String code ="";
        for (int i = 0;i<6;i++){
            int i1 = random.nextInt(10);
            code += i1;
        }
        return code;
    }
}
